package noticeservice

import (
	"errors"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/enum/admin/noticeenum"
	"yunj/pkg/yunj/app/model"
	"yunj/pkg/yunj/util"
)

// 通知创建
func Create(typ uint8, memberId uint64, desc string, dataId ...any) (err error) {
	notice := &model.AdminNotice{
		MemberId: memberId,
		Desc:     desc,
	}
	// type
	typeVal, ok := noticeenum.TypeEnum.IsValue(typ)
	if !ok {
		global.Logger.Error(util.FormatError(errors.New("通知类型错误！"), "通知类型错误！"))
		err = errors.New("通知类型错误！")
		return
	}
	notice.Type = typeVal
	// id
	id, idErr := util.SnowflakeId()
	if idErr != nil {
		global.Logger.Error(util.FormatError(idErr, "通知id生成错误！"))
		err = errors.New("通知id生成错误！")
		return
	}
	notice.Id = id
	// data_id
	if len(dataId) > 0 {
		dataIdStr, dataIdErr := util.ToString(dataId[0])
		if dataIdErr != nil {
			global.Logger.Error(util.FormatError(dataIdErr, "通知data_id转换错误！"))
			err = errors.New("通知data_id转换错误！")
			return
		}
		notice.DataId = dataIdStr
	}
	dbErr := global.MySQL.Create(notice).Error
	if dbErr != nil {
		global.Logger.Error(util.FormatError(dbErr, "通知创建失败！"))
		err = errors.New("通知创建失败！")
		return
	}
	return
}
